package logic

import (
	"context"
	"day15/api/pkg"
	"net/http"
	"path/filepath"

	"day15/api/internal/svc"
	"day15/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UploadLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUploadLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UploadLogic {
	return &UploadLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UploadLogic) Upload(r *http.Request) (resp *types.ApiResponse, err error) {
	// todo: add your logic here and delete this line
	file, header, err := r.FormFile("img")
	if err != nil {
		return &types.ApiResponse{
			Code: 0,
			Msg:  "文件获取失败",
			Data: nil,
		}, nil
	}
	defer file.Close()

	fileSuffix := filepath.Ext(header.Filename)
	if !(fileSuffix == ".png" || fileSuffix == ".jpg" || fileSuffix == ".jpeg") {
		return &types.ApiResponse{
			Code: 0,
			Msg:  "文件格式错误",
			Data: nil,
		}, nil
	}
	if header.Size > 2*1024*1024 {
		return &types.ApiResponse{
			Code: 0,
			Msg:  "文件过大",
			Data: nil,
		}, nil
	}
	url, err := pkg.FileUpload(file, header.Size)
	if err != nil {
		return &types.ApiResponse{
			Code: 0,
			Msg:  "文件上传失败",
			Data: nil,
		}, nil
	}
	return &types.ApiResponse{
		Code: 200,
		Msg:  "上传成功",
		Data: url,
	}, nil
}
